# 斗兽棋界面

import tkinter as tk
from tkinter import messagebox

from animal_chess import ChessColor, CHESS_TYPES_DIC, ChessError
from animal_chess.chess import ChessBoard

operated_positions = []


def click(x, y):
    chess = chess_board.chesses[x][y]
    button = buttons[x][y]
    if chess is None:
        if len(operated_positions) == 1:
            try:
                src_x = operated_positions[0][0]
                src_y = operated_positions[0][1]
                des_x = x
                des_y = y
                src_chess = chess_board.chesses[src_x][src_y]
                src_chess_type = src_chess.type
                src_chess_color = src_chess.color
                chess_board.move_chess(src_x, src_y, des_x, des_y)
            except ChessError as ce:
                tk.messagebox.showinfo('提示', ce.error_msg)
            else:
                buttons[src_x][src_y]['bg'] = 'black'
                buttons[src_x][src_y]['text'] = ''
                buttons[des_x][des_y]['bg'] = 'red' if src_chess_color == ChessColor.RED else 'blue'
                buttons[des_x][des_y]['text'] = CHESS_TYPES_DIC[src_chess_type]['label']
            finally:
                operated_positions.clear()
    elif chess.hidden:
        chess_board.reverse_chess(chess.x, chess.y)
        button['bg'] = 'red' if chess.color == ChessColor.RED else 'blue'
        button['fg'] = 'white'
        button['text'] = CHESS_TYPES_DIC[chess.type]['label']
        operated_positions.clear()
    else:
        operated_positions.append((x, y))
        if len(operated_positions) == 2:
            src_x = operated_positions[0][0]
            src_y = operated_positions[0][1]
            des_x = operated_positions[1][0]
            des_y = operated_positions[1][1]
            src_chess = chess_board.chesses[src_x][src_y]
            src_chess_type = src_chess.type
            src_chess_color = src_chess.color
            try:
                chess_board.eat_chess(src_x, src_y, des_x, des_y)
            except ChessError as ce:
                tk.messagebox.showinfo('提示', ce.error_msg)
            else:
                buttons[src_x][src_y]['bg'] = 'black'
                buttons[src_x][src_y]['text'] = ''
                buttons[des_x][des_y]['bg'] = 'red' if src_chess_color == ChessColor.RED else 'blue'
                buttons[des_x][des_y]['text'] = CHESS_TYPES_DIC[src_chess_type]['label']
            finally:
                operated_positions.clear()


window = tk.Tk()
window.title("斗兽棋")
window.resizable(0, 0)

chess_board = ChessBoard()
length = chess_board.length
width = chess_board.width
buttons = [[None for i in range(length)] for j in range(width)]
for x in range(width):
    for y in range(length):
        button = tk.Button(window, width=8, height=3)
        button.grid(row=x, column=y)
        button['command'] = lambda x=x, y=y: click(x, y)
        buttons[x][y] = button

window.mainloop()
